<?php

$totalCount = 0;
class importReasonTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
//     $this->addArguments(array(
//       new sfCommandArgument('file', sfCommandArgument::REQUIRED, 'My argument'),
//       new sfCommandArgument('totalCount', sfCommandArgument::REQUIRED, 'My argument'),
//     ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, '', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      new sfCommandOption('file', null, sfCommandOption::PARAMETER_REQUIRED, 'LUA File to convert', 'data/RPBot.lua'),
      // add your own options here
    ));

    $this->namespace        = 'raidpoints';
    $this->name             = 'importReason';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [import|INFO] task does things.
Call it with:

  [php symfony import|INFO]
EOF;
  }

  public function doLogSection($section, $message, $size = NULL, $style ='INFO')
  {
      global $totalCount;

      $q = Doctrine::getTable("DataImportStatus")
          ->createQuery()
          ->orderBy("date desc")
          ->limit(1);
      $r = $q->execute();

      $is = new DataImportStatus();
      $is->setDate(gmdate("Y-m-d H:i:s", time()));
      $is->setStatus($section);
      $is->setText($message);
          if ($r->count() > 0)
              $is->setStatustotal($r->getFirst()->getStatustotal());
          else
              $is->setStatustotal($totalCount);
      if (isset($size))
      {
          $is->setStatusbar($size);
          $size = null;
      }
      elseif ($r->count() == 1)
      {
          $is->setStatusbar($r->getFirst()->getStatusbar()+1);
      }
      else
      {
          $is->setStatusbar(0);
      }
      $is->save();
      $this->logsection($section, $message, $size, $style);
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
    // add your code here
    //

    global $totalCount;
    $totalCount = 0;
    $log=1;
    
    $query = Doctrine::getTable("DataImport")
        ->createQuery()
        ->select('SUM(size)');
    $result = $query->execute();
    if ($result->count() > 0)
    {
        $temp = $result->getFirst()->toArray();
        $totalCount = $temp['SUM'];
    }
    else
    {
        exit();
    }

	sleep(rand(1, 5));
    $query = Doctrine::getTable("DataImport")
        ->createQuery()
        ->select("*")
		->where("inprogress=?", 0)
        ->limit(1);
    $dataArray = $query->execute();
    if ($dataArray->count() == 0)
    {
        exit();
    }
	$dataArray->getFirst()->setInprogress(1);
	$dataArray->getFirst()->save();
    $data = unserialize($dataArray->getFirst()->getText());

    if (is_array($data['actiontime']))
    {
        $this->doLogSection("Working", "Misc");
    }
    else
    {
        $this->doLogSection("Working", "Date: ".($data['actiontime']));
    }

    $query = Doctrine::getTable("Raid")
        ->createQuery()
        ->where("id=?", $data['raid']);
    $result = $query->execute();
    $r = null;
    if ($result->count() > 0)
        $r = $result->getFirst();

//    $query = Doctrine::getTable("Officer")
//        ->createQuery()
//        ->where("id=?", 0);
//    $result = $query->execute();
//    $officer = $result->getFirst();

    $type = array("P" => "P", "I" => "I");
//    $query = Doctrine::getTable("TType")
//        ->createQuery();
//        //->where("ttype=?", "P");
//    $result = $query->execute();
//
//    foreach ($result as $t)
//    {
//        $type[$t['ttype']] = $t;
//    }

    $action = array("Insert" => "I", "Update" => "U", "Delete" => "D");
//    $query = Doctrine::getTable("AAction")
//        ->createQuery();
//        //->where("ttype=?", "P");
//    $result = $query->execute();
//
//    foreach ($result as $a)
//    {
//        $action[$a['name']] = $a;
//    }

    $actiont = $r->getVersion();
    $actiontime = 0;
    if (!is_array($data['actiontime']))
    {
        $actiontime = ($data['actiontime']);
        if ($actiontime > $actiont)
            $actiont = $actiontime;
    }

    $reason = null;
    $array = (is_array($data['actiontime']) ? $data['actiontime'] : $data['data']);

    $inc = 0;
    foreach ( $array as $player => $ev)
    {
        if (isset($data["playerList"][($player)]))
        {
            $e = $ev;
            if (is_array($data['actiontime']))
            {
                foreach ($ev as $at => $eve)
                {
                    $actiontime = $at;
                    $e = $eve;
                    break;
                }
            }

            if (!$reason || is_array($data['actiontime']))
            {
                $str = $e["reason"];
                preg_match_all('/[^|]+/i', $str, $words);
                if ( count($words[0]) == 5 )
                {
                    $rea = substr($words[0][2], 1);
                    if (substr($rea, 0, 1) != "[")
                        $rea = "[".$rea;
                    if (substr($rea, -1, 1) != "]")
                        $rea = $rea."]";
                    $str = "|".$words[0][0]."|".$words[0][1]."|h".$rea."|h|r";
                    //$str = str_replace("'", "\\'", $str);
                    //echo $str;
                    //echo "update reason set name='".$str."' where id='".$reason['id']."'";
                    //mysql_query("update reason set name='".$str."' where id='".$reason['id']."'");
                    //echo mysql_error();
                }
                $query = Doctrine::getTable("Reason")
                    ->createQuery()
                    ->where("name=?", $str);
                $result = $query->execute();
                if ($result->count() > 0)
                    $reason = $result->getFirst();
                else
                {
                    $reason = new Reason();
                    $reason->setName($str);
                    $reason->save();
                }
            }
            $query = Doctrine::getTable("History")
                ->createQuery()
                ->where("raidid=?", $data['raid'])
                ->andWhere("playerid=?", $data["playerList"][($player)])
                ->andWhere("dt=?", $e['datetime']);
            $result = $query->execute();
            if ($result->count() == 0 || $e['ty'] != 'I')
            {
                $history = new History();
                $history->fromArray($e);

                $waitlist = 0;
                if ($e["waitlist"] == 1)
                    $waitlist = 1;
                $history->setWaitlistflag($waitlist);
                $history->setZoneid(0);

                //echo "- dates - ";
                $history->setSavedate(gmdate("Y-m-d H:i:s", $actiontime));
                if (!isset($e["actiontime"]))
                    $e["actiontime"] = $e["datetime"];
                $history->setActiondate(gmdate("Y-m-d H:i:s", $e["actiontime"]));
                $history->setDt(gmdate("Y-m-d H:i:s", $e["datetime"]));
                //$history->setCreatedBy(1);
                $history->setRaid($r);

                $history->setTtype($type[$e['ty']]);
                $history->setAaction($action[$e["action"]]);
                $history->setReason($reason);

                $history->setPlayerid($data["playerList"][($player)]);

                try
                {
                    $history->trySave();
                    $this->doLogSection("Working", "New Record: ".$history->getPlayer()->getFullname()." - ".$history->getDt()." ".$history->getValue());
                }
                catch (exception $ex)
                {
                    $inc++;
                    //$this->doLogSection("Working", "Old Record: ".$history->getPlayer()->getFullname()." - ".$history->getDate()." ".$history->getValue());
                }
            }
//            else
//            {
//                //$this->doLogSection("Working", "Old Record: ".$history->getPlayer()->getFullname()." - ".$history->getDate()." ".$history->getValue());
//            }
        }
    }
    if ($actiont != $r->getVersion())
    {
        $r->setVersion($actiont);
        $r->save();
    }
    $this->doLogSection("Working", "Finished Date: ".($data['actiontime']), $inc);
    $dataArray->getFirst()->delete();

    /*
    $r = Doctrine::getTable("History")->getLastLog('2009-07-05 17:01:59', 10, 1);
    $r = $r->getFirst();

    $r = Doctrine::getTable("PlayerHistory")->updatePoints(2, 1);

    $newHistory = new History();
    $newHistory->setDate('2009-07-05 17:01:59');
    $newHistory->setActiondate('2009-07-05 17:02:51');
    $newHistory->setSavedate($newHistory->getActiondate());
    $newHistory->setLogdate(time());
    $newHistory->setLogcomment(' ');
    $newHistory->setComment(' ');
    $newHistory->setItemid(0);
    $newHistory->setOfficerid(0);
    $newHistory->setPlayerid(10);
    $newHistory->setRaidid(1);
    $newHistory->setReasonid(831);
    $newHistory->setTtype('I');
    $newHistory->setValue('0');
    $newHistory->setWaitlistflag(0);
    $newHistory->setZoneid(0);
    $newHistory->setAaction("D");
    $newHistory->save();

    $this->logsection("do-nothing", "I did nothing...");
    //print_r($r->getAction());
    */


  }
}
